﻿using Halcon二次开发.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon二次开发.Controller.数据加载与保存
{
    internal class LoadData
    {
        public Dictionary<string, string> GetData(string path)
        {
            Dictionary<string, string> dis= HelpJsons.Read(path);
            return dis;
        }

        /// <summary>
        /// //加载数据所有窗体
        /// </summary>
        /// <param name="path">Json文件路径</param>
        /// <param name="form">窗体对象</param>
        /// <param name="userControls">有node属性的窗体可以将这个对象存进来，就是PMA用的是自定义控件的窗体</param>
        public void LoadDatas(string path,Form form,List<UserControl> userControls=null)
        {
            Dictionary<string, string> dis = GetData(path);
            if (dis!=null)
            {
                //判断有没有这个文件Json
                if (File.Exists(path))
                {
                    foreach (Control conts in form.Controls)
                    {
                        //找子控件
                        Next(conts, dis);
                    }
                }
                if (userControls != null)//处理自定义控件的存值问题
                {
                    try
                    {
                        foreach (var item in userControls)
                        {
                            foreach (Control conts in item.Controls)
                            {
                                if (conts.Tag != null)
                                {
                                    foreach (var ds in dis)
                                    {
                                        if (conts.Tag.Equals(ds.Key))
                                        {
                                            conts.Text = ds.Value;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex) { }
                }
            }
        }
        /// <summary>
        /// 递归找子控件
        /// </summary>
        public void Next(Control conts, Dictionary<string, string> dis)
        {
            foreach (Control cont in conts.Controls)
            {
                if (cont.Tag!=null)
                {
                    if (cont.Tag.ToString().Length > 0)
                    {
                        foreach (var item in dis)
                        {
                            if (item.Key.Equals(cont.Tag.ToString()))
                            {
                                cont.Text = item.Value;
                            }
                        }
                    }
                }
                //找子控件
                Next(cont, dis);
                
            }
        }
    }
}
